package com.tanhua.dubbo.utils;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class TimeLineService {
    @Autowired
    private MongoTemplate mongoTemplate;


    @Async("tanhuaPool")
    public void saveTimeLine(Movement movement) {
        String name = Thread.currentThread().getName();
        System.out.println("保存时间线数据的线程 ：" + name);
        try{
            Thread.sleep(5000);

        }catch (Exception e){
            e.printStackTrace();
        }
        //2. 查询当前用户的所有好友
        Criteria criteria = Criteria.where("userId").is(movement.getUserId());
        Query query = Query.query(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        //3.更新好有时间线表
        for (Friend friend : friends) {
            MovementTimeLine line = new MovementTimeLine();
            line.setUserId(movement.getUserId());
            line.setFriendId(friend.getFriendId());
            line.setCreated(System.currentTimeMillis());
            line.setMovementId(movement.getId());
            mongoTemplate.save(line);
        }
    }
}
